// sign.js —— 小程序可用版，无依赖
const key = 'my_secret_key'; // 简单签名密钥

// 手写 Base64 编码/解码
const b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function b64Encode(str) {
  let out = "", i = 0;
  let c1, c2, c3;
  const len = str.length;
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      out += b64chars.charAt(c1 >> 2);
      out += b64chars.charAt((c1 & 0x3) << 4);
      out += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      out += b64chars.charAt(c1 >> 2);
      out += b64chars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      out += b64chars.charAt((c2 & 0xF) << 2);
      out += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    out += b64chars.charAt(c1 >> 2);
    out += b64chars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    out += b64chars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    out += b64chars.charAt(c3 & 0x3F);
  }
  return out;
}

function b64Decode(str) {
  let out = "", i = 0;
  let c1, c2, c3, c4;
  str = str.replace(/[^A-Za-z0-9\+\/]/g, "");
  while (i < str.length) {
    c1 = b64chars.indexOf(str.charAt(i++));
    c2 = b64chars.indexOf(str.charAt(i++));
    c3 = b64chars.indexOf(str.charAt(i++));
    c4 = b64chars.indexOf(str.charAt(i++));
    out += String.fromCharCode((c1 << 2) | (c2 >> 4));
    if (c3 != 64) out += String.fromCharCode(((c2 & 15) << 4) | (c3 >> 2));
    if (c4 != 64) out += String.fromCharCode(((c3 & 3) << 6) | c4);
  }
  return out;
}

// 简单 XOR 签名
function xorCipher(data, key) {
  let result = '';
  for (let i = 0; i < data.length; i++) {
    result += String.fromCharCode(data.charCodeAt(i) ^ key.charCodeAt(i % key.length));
  }
  return result;
}

// 生成签名
export function getSign(data) {
  if (!data || typeof data !== 'string') throw new Error('输入数据无效');
  const xored = xorCipher(data, key);
  return b64Encode(xored);
}

// 验证签名
export function verifySign(data, signature) {
  if (!data || typeof data !== 'string' || !signature || typeof signature !== 'string') {
    throw new Error('输入数据无效');
  }
  const decoded = b64Decode(signature);
  const expected = xorCipher(data, key);
  return decoded === expected;
}